<?php
class model_autogames extends base_model
{
    public function __construct() {
        // 指定允许其他域名访问
        header('Access-Control-Allow-Origin:*');
        // 响应类型
        header('Access-Control-Allow-Methods:*');
        // 响应头设置
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        //默认不用登录
        $this->usercheck = false;
        parent::__construct();
    }

    # region 自助发包
    public function mod_autosend_togame($gameid)
    {
        $paras['cmd'] = 'sendred';
        $paras['needusernum'] = 5;
        $paras['remoteip'] = '2130706433';
        $paras['nowtime'] = time();
        $paras['ws'] = 0; // 尾数
        $paras['coin'] = 0;
        if($gameid==3)
        {
            $paras['ws'] = mt_rand(0,9);
        }

        $coinlist = array(
            1 => '10,10,10,10,20,30,50,100,200',
            2 => '5,5,5,5,5,10,20,30,50,100',
            3 => '10,10,10,10,20,30,50,100,200',
            4 => '10,10,10,10,20,30,50,100,200',
            5 => '5,5,5,5,5,10,20,30,50',
        );


        $game['game'] = $this->getRow('@@games','*',array('id'=>$gameid));
        $game['odds'] = $this->db->query('SELECT * FROM `@@games_odds` WHERE `gameid`='.$gameid, 3);


        //红包的投注金额
        $testMinCoin = explode(',', $coinlist[$gameid]);//$game['game']['betscoinlist']);
        $paras['coin'] = intval($testMinCoin[0]);
        //随机金额
        $randcoin = array_rand($testMinCoin);
        $paras['coin'] = $testMinCoin[$randcoin];

        $betCoin = $paras['coin'];
        # 红包的金额
        $redcoin = $betCoin;
        //检测包的数量是否正确
        $testNeedUser = explode(',', $game['game']['manymen']);
        # 随机包数发送
        $paras['needusernum'] = $testNeedUser[0]; //array_rand($testNeedUser);;

        if(!in_array($paras['needusernum'], $testNeedUser))
        {
            core::error('包数不正确');
        }
        //本次发包所需要金币数量(有庄：游戏的人数-1 * $betCoin，无庄：$betCoin)
        //默认为无庄模式
        $betNeedCoin = $betCoin;

        $autoSendUids = $this->db->query('SELECT GROUP_CONCAT(uid) AS uids FROM @@autosend WHERE gameid='.$gameid,2);
        $autoSendUids = $autoSendUids['uids'];
        if(empty($autoSendUids)){
            exit(json_encode(array(
                'state' => 404,
                'msg' => '没有对应的发包用户',
            )));
        }

        if($game['game']['ishavebanker'])
        {
            //庄家的预计赔注（(人数 -1) * 红包的基本投注 * 最大赔率)）
            //找出游戏的最大赔率( 游戏的赔率是按从大到小的来排序，所以最上面一个就是最大的赔率，后台设置时需要把牌型最大的winsort值最为最大)
            $maxodds = $game['odds'][0]['odds'];

            # 如果有庄但没有固定发包金额的
            $betNeedCoinRed = $game['game']['establishcoin'] > 0 ? $game['game']['establishcoin'] : $betCoin;
            //-----
            $betNeedCoin = (($paras['needusernum'] - 1) * $betCoin * $maxodds);

            $users = $this->db->query('SELECT uid,uno,nickname,username,coin AS usercoin,avatar,usertype FROM `@@users` WHERE `uid` IN('.$autoSendUids.') AND `coin`>='.($betNeedCoin + $betNeedCoinRed),3);
            $user = array_rand($users, 1);
            $user = $users[$user];


            //如果金币余额不足退出发包并提示玩家(创建房间的费用+预计全赔的金额)
            if($user['usercoin'] < ($betNeedCoin + $betNeedCoinRed))
            {
                core::error('余额不足'.$user['usercoin'].' < ' . ($betNeedCoin + $betNeedCoinRed));//10005; //金币不足
            }
        }else{
            $users = $this->db->query('SELECT uid,uno,nickname,username,coin AS usercoin,avatar,usertype FROM `@@users` WHERE `uid` IN('.$autoSendUids.') AND `coin`>='.($betCoin),3);
            $user = array_rand($users, 1);
            $user = $users[$user];

            //如果金币余额不足退出发包并提示玩家(创建房间的费用+预计全赔的金额)
            if($user['usercoin'] < ($betCoin))
            {
                core::error('余额不足'.$user['usercoin'].' < ' . $betCoin);
            }
        }
        //如果发送或投注的的金额小于或大于游戏参数设置的值，退出并提示玩家
        if($betCoin < $game['game']['minbetcoin'] || $betCoin > $game['game']['maxbetcoin'])
        {
            core::error('设置的金额不正确('.$game['game']['minbetcoin'].'-'.$game['game']['maxbetcoin'].')');
        }
        #region 开始发包记录
        // 产生期号

        $currentIssue = $this->getIssue($gameid);


        # 红包的金额
        if(floatval($game['game']['establishcoin']) > 0)
        {
            $redcoin = floatval($game['game']['establishcoin']);
        }
        //记录发包的记录
        $send_log = array(
            'issue' => $currentIssue,
            'uid' => $user['uid'],
            'nickname' => $user['nickname'],
            'cur' => 1, //一发红包默认就是有自己一个人参与进去
            'coin' => $betCoin, //这里是发包的金币数量，每个人，不是加倍后的 ,红包的投注金额
            'redcoin' => $redcoin, // 红包的金额
            'ip' => $paras['remoteip'],
            'begintimes' => $paras['nowtime'],
            'mantissa' => $paras['ws'],
            'overtime' => $game['game']['overtime'],
            'gameid' => $game['game']['id'],
            'need' => $paras['needusernum'],
            'usertype' => $user['usertype'],
        );

        $currentRedEnvelopesID = $this->db->insert('@@bets', $send_log);
        //发包金额，两种模式：有庄和无庄，
        //有庄的需要发一个固定金币的红包
        $this->db->transaction('begin');
        if(floatval($game['game']['establishcoin']) > 0)
        {
            //记录固定发包的帐变
            $this->set_coin(
                array(
                    'uid' => $user['uid'],
                    'coin' => (0 - floatval($game['game']['establishcoin'])),
                    'gameid' => $game['game']['id'],
                    'liqtype' => 1, //发包扣款
                    'ex1' => $currentRedEnvelopesID,
                    'ex2' => $currentIssue,
                )
            );
        }else{
            # 如果没有固定发包的金额就要扣除，所发红包的金额
            if($game['game']['ishavebanker']==1) {
                $this->set_coin(
                    array(
                        'uid' => $user['uid'],
                        'coin' => (0 - floatval($betCoin)),
                        'gameid' => $game['game']['id'],
                        'liqtype' => 1, //发包扣款
                        'ex1' => $currentRedEnvelopesID,
                        'ex2' => $currentIssue,
                    )
                );
            }
        }
        //创建房间所需要扣的金币帐变
        $this->set_coin(
            array(
                'uid' => $user['uid'],
                'coin' => (0 - floatval($betNeedCoin)),
                'gameid' => $game['game']['id'],
                'liqtype' => 15, //创建房间
                'ex1' => $currentRedEnvelopesID,
                'ex2' => $currentIssue,
            )
        );
        //把自己加入到参与抢红包的队列数据中
        $betslog = array(
            'uid' => $user['uid'],
            'issue' => $currentIssue,
            'gameid' => $game['game']['id'],
            'times' => $paras['nowtime'],
            'betcoin' => $send_log['coin'],
        );
        $this->db->insert('@@betslog', $betslog);
        $this->db->transaction('commit');
        #endregion 结束发包动作

        //组织要推送给玩家的数据
        $result['state'] = 200;
        $result['gameid'] = $game['game']['id'];
        $result['groupname'] = 'game_'.$game['game']['id'];
        $result['user'] = $user;
        unset($result['msgid']);
        $result['datas'] = array(
            'id'=> $currentRedEnvelopesID,
            'issue'=> $currentIssue,
            'nickname'=> $user['nickname'],
            'avatar' => $user['avatar'],
            'need' => $paras['needusernum'], //所需要的人数为前台提交的人数，但需在前面进行验证安全性
            'times' => $this->formatTimes($paras['nowtime']),
            'overtime' => $game['game']['overtime'], //发包时的超时时间即为默认的超时数值
            'cur'=>1,
            'coin'=>$betCoin,
            'mantissa' => (intval($game['game']['id'])==3 ? $paras['ws'] : ''),
            'usertype' => $user['usertype'],
            'ispass' => 0,
        );

        //创建新的Redis队列，以红包的期数为Group的ID
        //在Redis队列后面加入新的玩家号码，如果不存在即创建一个新的
        $this->redis->rpush('games_doing_'.$currentIssue, $user['uno']);
        return $result;
    }
    # endregion

    # region 找出批定游戏正在进行的红包
    public function mod_autogrob($gameid)
    {
        # 随机排序
        $sql = "SELECT id FROM `@@bets` WHERE `gameid`=".$gameid." AND `state`=0 AND UNIX_TIMESTAMP() - `begintimes` <=180 AND `pass`='' ORDER BY RAND() LIMIT 1";
        $data = $this->db->query($sql,2);
        $id = $data['id'];
        if(empty($id)) return false;
        //$sql = "SELECT * FROM `@@bets` WHERE `gameid`=".$gameid." AND `state`=0 AND UNIX_TIMESTAMP() - `begintimes` <=180 AND `pass`='' ORDER BY `coin` ASC LIMIT 1";
        $sql = "SELECT * FROM `@@bets` WHERE `id`=".$id." LIMIT 1";
        $data = $this->db->query($sql,2);
        return $data;
    }
    # endregion

    # region 取出一个自动抢玩的玩家
    public function mod_autogrobuser($red)
    {
        if($red['usertype']==0){
            $usertype = ' AND U.`usertype`=0';
        }else{
            $usertype = ' AND U.`usertype`>=1';
        }
        # 找出已参与的玩家
        $sql = "SELECT GROUP_CONCAT(uid) AS _UIDS FROM `@@betslog` WHERE `gameid`=".$red['gameid']." and `issue`='".$red['issue']."'";
        $grabuser = $this->db->query($sql,2);
        $uids = empty($grabuser['_UIDS']) ? '' : ','.$grabuser['_UIDS'];
        $sql = 'SELECT U.* FROM `@@autosend` A,`@@users` U WHERE A.`uid`=U.`uid` AND A.`uid` NOT IN(0'.$uids.') AND A.`gameid`='.$red['gameid'].' '.$usertype;
        $data = $this->db->query($sql,3);
        if($data) {
            $user = array_rand($data, 1); // array_rand(): Array is empty
            $data = $data[$user];
            if ($data) {
                $update = $this->mod_updatetoken($data['uid'], $data['uno'], $data['token']);
                $data['webtoken'] = $update['webtoken'];
                $data['lastlogintimes'] = $update['lastlogintimes'];
            }
        }
        return $data;
    }
    # endregion

    # region 自动登录并更新用户信息
    public function mod_updatetoken($uid,$uno,$token)
    {
        # 更新用户的token
        $token = $this->settoken($uno, $token);
        $times = time();
        $sql = "UPDATE `@@users` SET `webtoken`='".$token."', `lastlogintimes`=".$times." WHERE `uid`=".$uid." LIMIT 1";
        $this->db->query($sql, 1);
        return array(
            'webtoken' => $token,
            'lastlogintimes' => time(),
        );
    }
    # endregion

    # region 取游戏的参数不包括赔率
    /**
     * 取游戏的参数不包括赔率
     * @param $gameid
     * @return mixed
     */
    public function mod_getGameForID($gameid)
    {
        $redis_key = 'games_item_forid_'.$gameid;
        if($this->redis->exists($redis_key))
        {
            $data = $this->redisGet($redis_key);
        }else {
            $where = "`id`={$gameid}";
            $fields = "id, title, func, establishcost, ishavebanker, establishcoin, manymen, custombetscoin, betscoinlist, minbetcoin, maxbetcoin, overtime, maxodds, state, passcoin";
            $tablename = "@@games";
            $sql = "SELECT {$fields} FROM `{$tablename}` WHERE {$where}";
            $data = $this->db->query($sql,2);
            $this->redisSet($redis_key, $data);
        }
        return $data;
    }
    # endregion
}